package com.jtframework.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class PassWordWithSaltUtil {

    /**
     * 生成盐值
     * @return
     */
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    /**
     * 计算hahs 值
     * @param password
     * @return
     */
    public static String hashPasswordWithSalt(String password) {
        return hashPasswordWithSalt(password,generateSalt());
    }


    /**
     * 计算hahs 值
     * @param password
     * @param salt
     * @return
     */
    public static String hashPasswordWithSalt(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(Base64.getDecoder().decode(salt));
            byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : hashedPassword) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验密码
     * @param inputPass 输入的密码
     * @param salt 盐值
     * @param storedHashedPassword  存储的密码 hash
      * @return
     */
    public static boolean checkPassword(String inputPass,String salt,String storedHashedPassword){
        String inputHashedPassword = hashPasswordWithSalt(inputPass, salt);
        return inputHashedPassword.equals(storedHashedPassword);
    }

}
